﻿using System;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;
using Entity;
using NLog;
using System.Linq;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
using System.Drawing;
using System.Diagnostics;
/// <summary>
/// Summary description for FormsFunction
/// </summary>
public class FormsFunction
{

    #region Variables
    private static XmlDocument xmlDoc = null;
    private static Logger _logger = LogManager.GetCurrentClassLogger();
    private static string[] mobileDevices = new string[] {"iphone","ppc",
                                                      "windows ce","blackberry",
                                                      "opera mini","mobile","palm",
                                                      "portable","opera mobi" };
    #endregion

    /// <summary>
    /// Retrieve Web Config
    /// </summary>
    /// <returns>retrive SiteConfiguration object</returns>
    public static SiteConfiguration RetrieveWebConfig()
    {
        try
        {
            SiteConfiguration objSiteConfiguration = new SiteConfiguration();
            using (StreamReader objStreamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/Settings_App/Settings.xml")))
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(objStreamReader.ReadToEnd());
                if (xmlDoc != null)
                {
                    XmlNodeList xmlNodeSiteName = xmlDoc.GetElementsByTagName("SiteName");
                    XmlNodeList xmlNodeSiteMetaDescription = xmlDoc.GetElementsByTagName("SiteMetaDescription");
                    XmlNodeList xmlNodeSiteMetaKeywords = xmlDoc.GetElementsByTagName("SiteMetaKeywords");
                    XmlNodeList xmlNodeSiteOffline = xmlDoc.GetElementsByTagName("SiteOffline");
                    XmlNodeList xmlNodeLogStatus = xmlDoc.GetElementsByTagName("LogStatus");
                    XmlNodeList xmlNodeLogPath = xmlDoc.GetElementsByTagName("LogPath");
                    XmlNodeList xmlNodeCacheStatus = xmlDoc.GetElementsByTagName("CacheStatus");
                    XmlNodeList xmlNodeSessionLifetime = xmlDoc.GetElementsByTagName("SessionLifetime");
                    XmlNodeList xmlNodeTestServer = xmlDoc.GetElementsByTagName("TestServer");
                    XmlNodeList xmlNodeDatabaseType = xmlDoc.GetElementsByTagName("DatabaseType");
                    XmlNodeList xmlNodeHost = xmlDoc.GetElementsByTagName("Host");
                    XmlNodeList xmlNodeDatabaseUsername = xmlDoc.GetElementsByTagName("DatabaseUsername");
                    XmlNodeList xmlNodeDatabasePassword = xmlDoc.GetElementsByTagName("DatabasePassword");
                    XmlNodeList xmlNodeDatabaseName = xmlDoc.GetElementsByTagName("DatabaseName");
                    XmlNodeList xmlNodeFromEmail = xmlDoc.GetElementsByTagName("FromEmail");
                    XmlNodeList xmlNodeFromName = xmlDoc.GetElementsByTagName("FromName");
                    XmlNodeList xmlNodeSMTPAuthentication = xmlDoc.GetElementsByTagName("SMTPAuthentication");
                    XmlNodeList xmlNodeSMTPSecurity = xmlDoc.GetElementsByTagName("SMTPSecurity");
                    XmlNodeList xmlNodeSMTPPort = xmlDoc.GetElementsByTagName("SMTPPort");
                    XmlNodeList xmlNodeSMTPUsername = xmlDoc.GetElementsByTagName("SMTPUsername");
                    XmlNodeList xmlNodeSMTPPassword = xmlDoc.GetElementsByTagName("SMTPPassword");
                    XmlNodeList xmlNodeSMTPHost = xmlDoc.GetElementsByTagName("SMTPHost");
                    XmlNodeList xmlNodeIsStreamLive = xmlDoc.GetElementsByTagName("IsStreamLive");

                    objSiteConfiguration.SiteName = xmlNodeSiteName[0].InnerText;
                    objSiteConfiguration.MetaDescription = xmlNodeSiteMetaDescription[0].InnerText;
                    objSiteConfiguration.MetaKeywords = xmlNodeSiteMetaKeywords[0].InnerText;
                    objSiteConfiguration.SiteOffline = xmlNodeSiteOffline[0].InnerText;
                    objSiteConfiguration.LogStatus = xmlNodeLogStatus[0].InnerText;
                    objSiteConfiguration.LogPath = xmlNodeLogPath[0].InnerText;
                    objSiteConfiguration.CacheStatus = xmlNodeCacheStatus[0].InnerText;
                    objSiteConfiguration.SessionLifetime = Convert.ToInt16(xmlNodeSessionLifetime[0].InnerText);
                    objSiteConfiguration.DatabaseType = xmlNodeDatabaseType[0].InnerText;
                    objSiteConfiguration.Host = xmlNodeHost[0].InnerText;
                    objSiteConfiguration.DatabaseUsername = xmlNodeDatabaseUsername[0].InnerText;
                    objSiteConfiguration.DatabasePassword = xmlNodeDatabasePassword[0].InnerText;
                    objSiteConfiguration.DatabaseName = xmlNodeDatabaseName[0].InnerText;
                    objSiteConfiguration.FromEmail = xmlNodeFromEmail[0].InnerText;
                    objSiteConfiguration.FromName = xmlNodeFromName[0].InnerText;
                    objSiteConfiguration.SMTPAuthentication = xmlNodeSMTPAuthentication[0].InnerText;
                    objSiteConfiguration.SMTPSecurity = Convert.ToInt16(xmlNodeSMTPSecurity[0].InnerText);
                    objSiteConfiguration.SMTPPort = Convert.ToInt16(xmlNodeSMTPPort[0].InnerText);
                    objSiteConfiguration.SMTPUsername = xmlNodeSMTPUsername[0].InnerText;
                    objSiteConfiguration.SMTPPassword = xmlNodeSMTPPassword[0].InnerText;
                    objSiteConfiguration.SMTPHost = xmlNodeSMTPHost[0].InnerText;
                    objSiteConfiguration.IsLiveStreamEnable = Convert.ToInt16(xmlNodeIsStreamLive[0].InnerText);
                }
            }
            return objSiteConfiguration;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::RetrieveWebConfig:::" + ex.Message);
            throw ex;
        }
    }

    /// <summary>
    /// UpdateWebConfig
    /// </summary>
    /// <param name="objSiteConfiguration">set SiteConfiguration object</param>
    public static void UpdateWebConfig(SiteConfiguration objSiteConfiguration)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath("~/Settings_App/Settings.xml"));
            doc.SelectSingleNode("//SiteName").InnerText = objSiteConfiguration.SiteName;
            doc.SelectSingleNode("//SiteMetaDescription").InnerText = objSiteConfiguration.MetaDescription;
            doc.SelectSingleNode("//SiteMetaKeywords").InnerText = objSiteConfiguration.MetaKeywords;
            doc.SelectSingleNode("//SiteOffline").InnerText = objSiteConfiguration.SiteOffline;
            doc.SelectSingleNode("//LogStatus").InnerText = objSiteConfiguration.LogStatus;
            doc.SelectSingleNode("//LogPath").InnerText = objSiteConfiguration.LogPath;
            doc.SelectSingleNode("//CacheStatus").InnerText = objSiteConfiguration.CacheStatus;
            doc.SelectSingleNode("//SessionLifetime").InnerText = objSiteConfiguration.SessionLifetime.ToString();
            doc.SelectSingleNode("//DatabaseType").InnerText = objSiteConfiguration.DatabaseType;
            doc.SelectSingleNode("//Host").InnerText = objSiteConfiguration.Host;
            doc.SelectSingleNode("//DatabaseUsername").InnerText = objSiteConfiguration.DatabaseUsername;
            doc.SelectSingleNode("//DatabasePassword").InnerText = objSiteConfiguration.DatabasePassword;
            doc.SelectSingleNode("//DatabaseName").InnerText = objSiteConfiguration.DatabaseName;
            doc.SelectSingleNode("//FromEmail").InnerText = objSiteConfiguration.FromEmail;
            doc.SelectSingleNode("//FromName").InnerText = objSiteConfiguration.FromName;
            doc.SelectSingleNode("//SMTPAuthentication").InnerText = objSiteConfiguration.SMTPAuthentication;
            doc.SelectSingleNode("//SMTPSecurity").InnerText = objSiteConfiguration.SMTPSecurity.ToString();
            doc.SelectSingleNode("//SMTPPort").InnerText = objSiteConfiguration.SMTPPort.ToString();
            doc.SelectSingleNode("//SMTPUsername").InnerText = objSiteConfiguration.SMTPUsername;
            doc.SelectSingleNode("//SMTPPassword").InnerText = objSiteConfiguration.SMTPPassword;
            doc.SelectSingleNode("//SMTPHost").InnerText = objSiteConfiguration.SMTPHost;
            doc.SelectSingleNode("//IsStreamLive").InnerText = objSiteConfiguration.IsLiveStreamEnable.ToString();
            doc.Save(HttpContext.Current.Server.MapPath("~/Settings_App/Settings.xml"));
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::RetrieveWebConfig:::" + ex.Message);
            throw ex;
        }
    }

    /// <summary>
    /// This Methods Allow the Application to Send the Bugs Error to the Developer 
    /// </summary>
    /// <param name="sMailAccount">Set Email Address Developer Account "Set A String Value"</param>
    /// <param name="sPassword">Set Email Account Password Developer Account "Set A String Value"</param>
    /// <param name="sToUser">Set Email Address for How is recive Address Developer Account "Set A String Value"</param>
    /// <param name="sSubjectEmail">Set Email Subject "Set A String Value"</param>
    /// <param name="sMessageBody">Set Email Body Account "Set A String Value"</param>
    /// <returns>Retrun True if the Email Send Successfully otherwiaw return Flase</returns>
    public static bool SendMail(string sToUser, string sSubjectEmail, string sMessageBody)
    {
        try
        {
            //SiteConfiguration objSiteConfiguration = RetrieveWebConfig();
            var loginInfo = new NetworkCredential("livekoranet@gmail.com", "livekora_q1w2e3r4");
            var msg = new MailMessage { From = new MailAddress("livekoranet@gmail.com", "livekoranet@gmail.com") };
            msg.To.Add(new MailAddress(sToUser));
            msg.Subject = sSubjectEmail;
            msg.Body = sMessageBody;
            msg.IsBodyHtml = true;
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                UseDefaultCredentials = false,
                EnableSsl = true,
                Credentials = loginInfo
            };
            client.Send(msg);
            return true;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::SendMail:::" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// Bind Drop Down list Without Adding Default Item
    /// </summary>
    /// <param name="ddl"> Ref Drop Down List</param>
    /// <param name="strSPName"> Store Procedure Name</param>
    /// <param name="strTextField">Text Field Name</param>
    /// <param name="strValueField">Value Field Name</param>
    public static void BindDDL(ref DropDownList ddl, DataSet objDataSet, string strTextField, string strValueField)
    {
        try
        {
            BindDDL(ref ddl, objDataSet, strTextField, strValueField, "");
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::BindDDL:::" + ex.Message);
        }
    }

    /// <summary>
    /// Bind Drop Down list With Adding Default Item
    /// </summary>
    /// <param name="ddl">Ref Drop Down List</param>
    /// <param name="strSPName">Stored Procedure</param>
    /// <param name="strTextField">Text Field Name</param>
    /// <param name="strValueField">Value Field Name</param>
    /// <param name="strDefultItemText">Default Item Name, AND It Value Will be 0</param>
    public static void BindDDL(ref DropDownList ddl, DataSet objDataSet, string strTextField, string strValueField, string strDefultItemText)
    {
        try
        {

            DataSet ds = objDataSet;
            ddl.DataTextField = strTextField;
            ddl.DataValueField = strValueField;
            ddl.DataSource = ds;
            ddl.DataBind();
            if (strDefultItemText != string.Empty)
            {
                ListItem item = new ListItem();
                item.Text = strDefultItemText;
                item.Value = "-2";
                ddl.Items.Insert(0, item);
            }
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::BindDDL_2:::" + ex.Message);
        }
    }

    ///// <summary>
    ///// Determain the is device Mobile or not
    ///// </summary>
    ///// <param name="userAgent"></param>
    ///// <returns></returns>
    //public static bool IsMobileDevice(string userAgent)
    //{
    //    Regex b = new Regex(@"android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    //    Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|e\\-|e\\/|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\-|2|g)|yas\\-|your|zeto|zte\\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
    //    if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
    //    {
    //        return true;
    //    }
    //    else
    //    {
    //        return false;
    //    }

    //    //// TODO: null check
    //    //userAgent = userAgent.ToLower();
    //    //return mobileDevices.Any(x => userAgent.Contains(x));
    //}

    static Regex MobileCheck = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
    static Regex MobileVersionCheck = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);

    public static bool IsMobileDevice()
    {
        try
        {
            Debug.Assert(HttpContext.Current != null);
            bool bIsMobileDevice = false;
            if (HttpContext.Current.Request != null && HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {
                var u = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString();
                if (u.Length < 4)
                {
                    bIsMobileDevice = false;
                }

                if (MobileCheck.IsMatch(u) || MobileVersionCheck.IsMatch(u.Substring(0, 4)) || u.ToLower().Contains("android"))
                {
                    bIsMobileDevice = true;
                }
                return bIsMobileDevice;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::IsMobileDevice:::" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    private void VaryQualityLevel()
    {
        try
        {
            // Get a bitmap.
            Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);


            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);

            myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(@"c:\TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);

            // Save the bitmap as a JPG file with zero quality level compression.
            myEncoderParameter = new EncoderParameter(myEncoder, 0L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(@"c:\TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters);
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::VaryQualityLevel:::" + ex.Message);
        }

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="format"></param>
    /// <returns></returns>
    private ImageCodecInfo GetEncoder(ImageFormat format)
    {
        try
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::GetEncoder:::" + ex.Message);
            return null;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="path"></param>
    /// <param name="img"></param>
    /// <param name="quality"></param>
    public static void SaveJpeg(string path, System.Drawing.Image img, int quality)
    {
        try
        {
            if (quality < 0 || quality > 100)
                throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
            EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            img.Save(path, jpegCodec, encoderParams);
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::SaveJpeg:::" + ex.Message);
        }
    }

    /// <summary> 
    /// Returns the image codec with the given mime type 
    /// </summary> 
    private static ImageCodecInfo GetEncoderInfo(string mimeType)
    {
        try
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::GetEncoderInfo:::" + ex.Message);
            return null;
        }
    }

    /// <summary>
    /// Sets up the current page or handler to use GZip through a Response.Filter
    /// IMPORTANT:  
    /// You have to call this method before any output is generated!
    /// </summary>
    public static void GZipEncodePage()
    {
        try
        {
            HttpResponse Response = HttpContext.Current.Response;

            if (IsGZipSupported())
            {
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
                if (AcceptEncoding.Contains("deflate"))
                {
                    Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "deflate");
                }
                else
                {
                    Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "gzip");
                }
            }

            Response.AppendHeader("Vary", "Content-Encoding");
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::GZipEncodePage:::" + ex.Message);
        }
    }

    /// <summary>
    /// Determines if GZip is supported
    /// </summary>
    /// <returns></returns>
    public static bool IsGZipSupported()
    {
        try
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            string IsPartial = HttpContext.Current.Request.Headers["x-microsoftajax"];
            if (!string.IsNullOrEmpty(AcceptEncoding) &&
                 AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))
                if (string.Compare("Delta=true", IsPartial, true) == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::IsGZipSupported:::" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="nEmailTempleteID"></param>
    /// <returns></returns>
    public static int SendAndGetEmailTempleteByArabiSkyInfo(int nEmailTempleteID, string sEmailAddress, string sPassword)
    {
        try
        {
            string sEmailText = string.Empty;
            switch (nEmailTempleteID)
            {
                case 0:
                    //Send Email Activation First Time
                    using (StreamReader objStreamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/UserEmail/FirstEmail.htm")))
                    {
                        sEmailText = objStreamReader.ReadToEnd();
                    }
                    sEmailText = sEmailText.Replace("#UserEmailAddress#", sEmailAddress);
                    sEmailText = sEmailText.Replace("#UserPassword#", sPassword);
                    SendEmailServiceByLivekoraInfo(sEmailAddress, sEmailText, "موقع سماء العرب | تفعيل الحساب");
                    return 1;
                case 1:
                    //Send Email forget Password
                    using (StreamReader objStreamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/UserEmail/ForGetPasswordAccount.htm")))
                    {
                        sEmailText = objStreamReader.ReadToEnd();
                    }
                    sEmailText = sEmailText.Replace("#UserEmailAddress#", sEmailAddress);
                    sEmailText = sEmailText.Replace("#UserPassword#", sPassword);
                    SendEmailServiceByLivekoraInfo(sEmailAddress, sEmailText, "موقع سماء العرب | إستعادة كلمة المرور");
                    return 1;
                default:
                    return 0;
            }
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::SendEmailService:::" + ex.Message);
            return -1;
        }
    }



    /// <summary>
    /// Send Email Address For A User from our system
    /// </summary>
    /// <param name="sToEmailAddress">set Email Address to send the user "string value"</param>
    /// <param name="sEmailBody">set Email Body "string value"</param>
    /// <param name="sEmailSubject">set email Subject "string value"</param>
    /// <returns>return Success if send sucessfully otherwise return Execption</returns>
    public static int SendEmailServiceByLivekoraInfo(string sToEmailAddress, string sEmailBody, string sEmailSubject)
    {
        try
        {
            MailMessage message = new MailMessage("info@livekora.net", sToEmailAddress);
            SmtpClient smtpClient = new SmtpClient("smtpout.asia.secureserver.net", 80);
            smtpClient.EnableSsl = false;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential("info@livekora.net", "info_q1w2e3r4");
            smtpClient.Timeout = 10000;

            message.From = new MailAddress("info@livekora.net", "Livekora.net");
            message.Subject = sEmailSubject;
            message.Body = sEmailBody;
            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.UTF8Encoding.UTF8;
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            smtpClient.Send(message);
            return 1;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::SendEmailServiceByLivekoraInfo:::" + ex.Message);
            return SendEmailServiceByGmailCom(sToEmailAddress, sEmailBody, sEmailSubject);
        }
    }

    /// <summary>
    /// Send Email Address For A User from our system
    /// </summary>
    /// <param name="sToEmailAddress">set Email Address to send the user "string value"</param>
    /// <param name="sEmailBody">set Email Body "string value"</param>
    /// <param name="sEmailSubject">set email Subject "string value"</param>
    /// <returns>return Success if send sucessfully otherwise return Execption</returns>
    private static int SendEmailServiceByGmailCom(string sToEmailAddress, string sEmailBody, string sEmailSubject)
    {
        try
        {
            MailMessage mail = new MailMessage();
            mail.Subject = sEmailSubject;
            mail.From = new MailAddress("khodrog@gmail.com");
            mail.To.Add("khodrog@gmail.com");
            mail.Body = sEmailBody;
            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.EnableSsl = true;
            NetworkCredential netCre = new NetworkCredential("khodrog@gmail.com", "osm_kho_219700");
            smtp.Credentials = netCre;
            smtp.Timeout = 10000;
            smtp.Send(mail);
            return 1;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::SendEmailServiceByGmailCom:::" + ex.Message);
            return -1;
        }
    }

    #region Path Cookie
    public static void SetCookieValue(string sUserID, string sEmailAddress)
    {
        try
        {
            if (HttpContext.Current.Request.Cookies["LiveKoraCookie"] != null)
            {
                HttpContext.Current.Request.Cookies["LiveKoraCookie"].Expires = DateTime.Now.AddDays(-1);
            }
            HttpCookie cookie = new HttpCookie("LiveKoraCookie");
            cookie.Expires = DateTime.Now.AddDays(60);
            cookie.Name = "LiveKoraCookie";
            cookie.Value = EncryptionMethods.Encryption.Encrypt(sUserID + "|" + sEmailAddress);
            HttpContext.Current.Response.Cookies.Add(cookie);
            HttpContext.Current.Request.Cookies["LiveKoraCookie"].Expires = DateTime.Now.AddDays(60);
        }
        catch (Exception)
        {
            HttpContext.Current.Response.Cookies["LiveKoraCookie"].Expires = DateTime.Now.AddDays(-1);
        }
    }
    public static string[] GetLiveKoraCookie()
    {
        try
        {
            if (HttpContext.Current.Request.Cookies["LiveKoraCookie"] != null)
                return EncryptionMethods.Encryption.Decrypt(HttpContext.Current.Request.Cookies["LiveKoraCookie"].Value).Split('|');

            else
                return null;
        }
        catch (Exception ex)
        {
            _logger.Error("FormsFunction:::GetLiveKoraCookie:::" + ex.Message);
            return null;
        }
    }
    
    #endregion
}